package com.lauor.smpedr.core.helper;

import java.util.List;
import java.util.StringJoiner;

public class LogSqlHelper {

    public static String buildSqlLogStr(String sql, List paramList, int resultRows){
        if (paramList == null || paramList.isEmpty()) return "sql: " + sql;

        StringBuilder rsBuilder = new StringBuilder("sql: ");
        rsBuilder.append(sql)
                .append("\r\nparams: [");
        StringJoiner paramJoiner = new StringJoiner(", ");
        for (Object paramVal : paramList) {
            paramJoiner.add( String.valueOf(paramVal) );
        }
        rsBuilder.append( paramJoiner.toString() )
                .append("]")
                .append("\r\naffect rows: ")
                .append(resultRows);
        return rsBuilder.toString();
    }

    public static String buildSqlInsertLogStr(String sql, List<List> paramList, int affectRows){
        if (paramList == null || paramList.isEmpty()) return "sql: " + sql;

        StringJoiner paramsJoiner = new StringJoiner(",\r\n", "\r\nparams: [", "]");
        for (List list : paramList) {
            StringJoiner paramJoiner = new StringJoiner(", ", "(", ")");
            for (Object param : list) {
                paramJoiner.add( String.valueOf(param) );
            }
            paramsJoiner.add( paramJoiner.toString() );
        }
        StringBuilder rsBuilder = new StringBuilder("sql: ");
        rsBuilder.append(sql)
                .append( paramsJoiner.toString() )
                .append("\r\naffect rows: ")
                .append(affectRows);
        return rsBuilder.toString();
    }

    public static String buildSqlUpdateLogStr(String sql, List<List> valList, List paramList, int affectRows){
        if (paramList == null || paramList.isEmpty()) return "sql: " + sql;

        StringBuilder rsBuilder = new StringBuilder("sql: ");
        rsBuilder.append(sql);
        //values
        if ( valList != null && !valList.isEmpty() ){
            StringJoiner valuesJoiner = new StringJoiner(",\r\n", "\r\nvalues: [", "]");
            for (List values : valList) {
                StringJoiner paramJoiner = new StringJoiner(", ", "(", ")");
                for (Object value : values) {
                    paramJoiner.add( String.valueOf(value) );
                }
                valuesJoiner.add( paramJoiner.toString() );
            }
            rsBuilder.append( valuesJoiner.toString() );
        }
        //params
        if (paramList != null && !paramList.isEmpty()){
            StringJoiner paramJoiner = new StringJoiner(", ");
            for (Object paramVal : paramList) {
                paramJoiner.add( String.valueOf(paramVal) );
            }
            rsBuilder.append("\r\nparams: [")
                    .append( paramJoiner.toString() )
                    .append("]");
        }

        rsBuilder.append("\r\naffect rows: ")
                .append(affectRows);
        return rsBuilder.toString();
    }
}